package alert

import (
	"context"
	"errors"

	"yunzhan/alert-server/internal/svc"
	"yunzhan/alert-server/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type UpdateAlertRuleLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// NewUpdateAlertRuleLogic 更新告警规则
func NewUpdateAlertRuleLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UpdateAlertRuleLogic {
	return &UpdateAlertRuleLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *UpdateAlertRuleLogic) UpdateAlertRule(req *types.UpdateAlertRuleRequest) (resp *types.UpdateAlertRuleResponse, err error) {
	var updatedRules []*types.AlertRule

	for _, rule := range req.AlertRules {
		// 查找要更新的规则
		existingRule, err := l.svcCtx.AlertRuleModel.FindOne(rule.ID)
		if err != nil {
			return &types.UpdateAlertRuleResponse{
				Success: 500,
				Message: "告警规则更新失败",
				Error:   err.Error(),
			}, err
		}

		// 确保所有必填字段都有提供
		if rule.ComponentName == "" || rule.Metric == "" || rule.Operator == "" {
			errMsg := "component, metric, and operator fields cannot be empty"
			logx.Error(errMsg)
			return &types.UpdateAlertRuleResponse{
				Success: 500,
				Message: "Validation error",
				Error:   errMsg,
			}, errors.New(errMsg)
		}

		// 更新规则字段
		existingRule.ComponentName = rule.ComponentName
		existingRule.ComponentRole = rule.ComponentRole
		existingRule.Metric = rule.Metric
		existingRule.Operator = rule.Operator
		existingRule.Threshold = rule.Threshold
		existingRule.Enabled = rule.Enabled
		existingRule.NotificationConfig = rule.NotificationConfig

		// 更新数据库中的规则
		err = l.svcCtx.AlertRuleModel.Update(existingRule)
		if err != nil {
			logx.Errorf("failed to update alert rule with id %d: %v", rule.ID, err)
			return &types.UpdateAlertRuleResponse{
				Success: 500,
				Message: "告警规则更新失败",
				Error:   err.Error(),
			}, err
		}

		// 添加到已更新的规则列表
		updatedRules = append(updatedRules, existingRule)
	}

	// 返回更新成功的详细信息
	return &types.UpdateAlertRuleResponse{
		Success:      200,
		Message:      "告警规则更新成功",
		UpdatedRules: updatedRules,
	}, nil
}
